package com.geekcoding.geekoj.dto;

import cn.hutool.extra.spring.SpringUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.geekcoding.geekoj.entity.Question;
import com.geekcoding.geekoj.entity.Test;
import com.geekcoding.geekoj.entity.TestAnswer;
import com.geekcoding.geekoj.entity.UserEntity;
import com.geekcoding.geekoj.repository.TestAnswerRepository;
import com.geekcoding.geekoj.repository.UserEntityRepository;
import lombok.Builder;
import lombok.Data;

import java.util.*;

@Data
@Builder
public class QuestionDTO {

    private Question detail;

    private TestAnswer answer;

    private List<QuestionOption> options;

    private Test test;

    private User user;


    @Data
    static class QuestionOption{
        private String value;

        private String no;

        private Integer sort;
    }

    public static QuestionDTO convert(Question question, Test test) {
        if(Objects.isNull(question)){
            return null;
        }
        QuestionDTO questionDTO = QuestionDTO.builder().test(test).detail(question).build();
        if (Objects.nonNull(question.getOptions())) {
            JSONArray arr = JSONUtil.parseArray(question.getOptions());
            List<QuestionOption> optionList = new ArrayList<>(arr.size());
            arr.forEach(item -> optionList.add(JSONUtil.toBean(item.toString(), QuestionOption.class)));
            optionList.sort(Comparator.comparingInt(QuestionOption::getSort));
            questionDTO.setOptions(optionList);
        }
        TestAnswerRepository testAnswerRepository = SpringUtil.getBean(TestAnswerRepository.class);
        if (Objects.nonNull(test)) {
            Optional.ofNullable(testAnswerRepository.query(test, question)).ifPresent(questionDTO::setAnswer);
        }
        if (Objects.nonNull(questionDTO.getAnswer())) {
            UserEntityRepository userEntityRepository = SpringUtil.getBean(UserEntityRepository.class);
            Optional.ofNullable(userEntityRepository.queryById(questionDTO.getAnswer().getAnswerId())).ifPresent(questionDTO::setUser);
        }
        return questionDTO;
    }

}
